<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="3" :lg="7" :md="8" :sm="24">
            <a-form-model-item label="年级" prop="queryParam.gradeId">
              <!--              v-model="queryParam.gradeId"  对应java的Controller的接收参数vo对象的属性gradeId的值 -->
              <j-dict-select-tag v-model="queryParam.gradeId" placeholder="请选择年级" dictCode="cou_grade,grade_name,id,tenant_id  is not null order by  grade_order"/>
            </a-form-model-item>
          </a-col>
          <!--          <a-col :span="6">选中值：{{ formData.gradeId}}</a-col>-->


          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-model-item label="考试" prop="queryParam.examinationId">
              <j-dict-select-tag v-model="queryParam.examinationId" placeholder="请选择考试" dictCode="ach_examination,examination_name,id,del_flag  =0 and iz_open  =1 order by create_time  desc"/>
            </a-form-model-item>
          </a-col>
          <!--          <a-col :span="6">选中值：{{ queryParam.examinationId}}</a-col>-->

          <!--          <a-col :span="12">-->
          <!--            <a-form-model-item label="分类字典树" prop="selectGradeClass">-->
          <!--              &lt;!&ndash; pcode="B01" 是分类字典中的字典码&ndash;&gt;-->
          <!--              <j-category-select v-model="formData.selectGradeClass" pcode="B01" :multiple="true"/>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col :span="12">选中的值(v-model)：{{ formData.selectGradeClass }}</a-col>-->

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-model-item label="计分范围(多选)" prop="queryParam.achievementStatus">
              <j-multi-select-tag
                v-model="queryParam.achievementStatus"
                dictCode="achievement_status"
                placeholder="请选择">
              </j-multi-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <!--                <a-input placeholder="请输入科目" v-model="queryParam.subjectId"></a-input>-->
            <a-form-model-item label="科目" prop="queryParam.subjectId">
              <j-select-multiple placeholder="请选择科目" v-model="queryParam.subjectId" dictCode="cou_subject,subject_name,id" />
            </a-form-model-item>
          </a-col>

          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="trRow2Col" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
          <template v-if="toggleSearchStatus">
            <a-row :gutter="24">
              <!--          <a-col :span="12">选中的值(v-model)：{{ formData.achievementStatus }}</a-col>-->
              <a-col :xl="3" :lg="7" :md="8" :sm="24">
                <!--                <a-input placeholder="请输入科目" v-model="queryParam.subjectId"></a-input>-->
                <a-form-model-item label="班级" prop="queryParam.classId">
                  <j-select-multiple placeholder="请选择班级" v-model="queryParam.classId" dictCode="cou_class,class_name,id,class_iz_open  =1 and class_iz_delete  = 0 order by  class_order" />
                </a-form-model-item>
              </a-col>


              <!--            <a-col :span="2">(输入-1查总分)</a-col>-->
<!--              <a-col :xl="4" :lg="7" :md="8" :sm="24">-->
<!--                <a-form-model-item label="试卷" prop="queryParam.examinationPaperId">-->
<!--                  &lt;!&ndash;                  <j-select-multiple v-model="queryParam.examinationPaperId" :options="jSelectExaminationPaperId"/>&ndash;&gt;-->
<!--                  <j-select-multiple v-model="queryParam.examinationPaperId" dictCode="ach_examination_paper,examination_paper_name,id,iz_open =1 and del_flag =0  order by create_time desc" />-->
<!--                </a-form-model-item>-->
<!--              </a-col>-->
              <a-col :xl="4" :lg="7" :md="8" :sm="24">
                <!-- 取试卷的标准 或考试的标准 -->
                <a-form-model-item label="试卷分项" prop="queryParam.exaPapProItemId">
                  <j-select-multiple v-model="queryParam.exaPapProItemId" dictCode="ach_exam_paper_project_item,exa_pap_pro_item_name,id,iz_open =1 and del_flag =0  order by exa_pap_pro_item_order" />
                </a-form-model-item>
              </a-col>

              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <!-- 取试卷的标准 或考试的标准 -->
                <a-form-model-item label="评分标准" prop="queryParam.achievementStandardId">
                  <j-select-multiple v-model="queryParam.achievementStandardId" dictCode="ach_achievement_standard,achievement_standard_name,id,iz_open =1 and del_flag =0  order by achievement_standard_order" />
                </a-form-model-item>
              </a-col>


              <a-col :xl="4" :lg="7" :md="8" :sm="24">
                <a-form-model-item label="评分段位" prop="queryParam.achieveStandardItemId">
                  <!--                  <j-select-multiple v-model="queryParam.standItemId" :options="jSelectstandItemId"/>-->
                  <j-select-multiple v-model="queryParam.achieveStandardItemId" dictCode="ach_achieve_standard_item,stand_item_name,id,iz_open =1 and del_flag =0 order by exa_pap_pro_item_code" />
                </a-form-model-item>
              </a-col>
              <!--              <a-col :span="12">多选下拉框(v-model)：{{ queryParam.examinationPaperId }}</a-col>-->
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-form-item label = "成绩分值范围" prop="queryParam.achievementScore">
                  <label >[</label>
                  <a-input-number label = "分值范围:["  v-model ="queryParam.achievementScore_min" ></a-input-number>
                  <label >-</label>
                  <a-input-number label = "-"  v-model ="queryParam.achievementScore_max" ></a-input-number>
                  <label >)</label>

                </a-form-item>

              </a-col>



            </a-row>

          </template>

      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
<!--      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>-->
      <a-button type="primary" icon="download" @click="handleExportXls('班级考试分项成绩分析表')">导出</a-button>
<!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
<!--        <a-button type="primary" icon="import">导入</a-button>-->
<!--      </a-upload>-->
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
<!--      <a-dropdown v-if="selectedRowKeys.length > 0">-->
<!--        <a-menu slot="overlay">-->
<!--          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>-->
<!--        </a-menu>-->
<!--        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>-->
<!--      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        <span style="float:right;">
          <a @click="loadData()"><a-icon type="sync" />刷新</a>
          <a-divider type="vertical" />
          <a-popover title="自定义列" trigger="click" placement="leftBottom">
            <template slot="content">
              <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                <a-row style="width: 400px">
                  <template v-for="(item,index) in defColumns">
                    <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                        <a-col :span="12"><a-checkbox :value="item.dataIndex"><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox></a-col>
                    </template>
                  </template>
                </a-row>
              </a-checkbox-group>
            </template>
            <a><a-icon type="setting" />设置</a>
          </a-popover>
        </span>
      </div>

<!--      <div id="app">-->
<!--        <table class="table_default1" style="width: 400px;">-->
<!--          <tr>-->
<!--            <th v-for="item in tableHeader">-->
<!--              {{item}}-->
<!--            </th>-->
<!--          </tr>-->
<!--          <tr v-for="tr in tableBody">-->
<!--            <td v-for="td in tr">-->
<!--              {{td}}-->
<!--            </td>-->
<!--          </tr>-->
<!--        </table>-->
<!--      </div>-->
      <div >
        <a-table
          ref="table"
          size="middle"
          :scroll="{x:true}"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          class="j-table-force-nowrap"
          @change="handleTableChange">

        </a-table>

      </div>

    </div>

    <ach-class-subject-proj-score-modal ref="modalForm" @ok="modalFormOk"></ach-class-subject-proj-score-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import {getAction} from '@api/manage'
  import Vue from 'vue'
  import achClassSubjectProjScoreModal from './modules/AchClassSubjectProjScoreModal'
  import { getSubjectList, queryTeacherListBySubject } from '@api/commonAPI'

  export default {
    name: 'AchClassSubjectProjScoreList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      achClassSubjectProjScoreModal
    },
    data () {
      return {
        description: 'ach_class_subject_proj_score管理页面',
        disableMixinCreated : true, //默认初始状态不加载数据
        queryParam:{
          achievementStatus: '1,2,3',
        } ,
        //查询条件联动部分定义
        queryParamSelect: {
          examinationIdSelect: "ach_examination,examination_name,id,del_flag  =0 and iz_open  =1 order by create_time  desc",
          classIdSelect: "cou_class,class_name,id,class_iz_open  =1 and class_iz_delete  = 0 order by  class_order",
          examinationPaperIdSelect: "ach_examination_paper aep,aep.examination_paper_name,aep.id,aep.iz_open =1 and aep.del_flag =0  order by examination_paper_name",
          achievementStandardIdSelect: null,
          // "ach_achievement_standard aas inner join rel_ach_standard_distribution rasd on aas.id = rasd.achievement_standard_id,aas.achievement_standard_name,aas.id,aas.iz_open =1 and aas.del_flag =0 and rasd.paper_standard_effective =1",
          achieveStandardItemIdSelect: null,
          //"ach_achieve_standard_item,stand_item_name,id,iz_open =1 and del_flag =0 order by exa_pap_pro_item_code",
        },
        //表头
        columns:[],
        //列设置
        settingColumns:[],
        defColumns: [],
        //列定义 defColumns
        gudingColumns: [
          // {
          //   title: '#',
          //   dataIndex: '',
          //   key:'rowIndex',
          //   width:60,
          //   align:"center",
          //   customRender:function (t,r,index) {
          //     return parseInt(index)+1;
          //   }
          // },
          {
            title:'年级',
            align:"center",
            dataIndex: 'gradeName'
          },
          {
            title:'考试',
            align:"center",
            dataIndex: 'examinationName'
          },
          {
            title:'试卷',
            align:"center",
            dataIndex: 'examinationPaperName'
          },
          {
            title:'科目',
            align:"center",
            dataIndex: 'subjectName'
          },
          {
            title:'班级',
            align:"center",
            dataIndex: 'className'
          },
          {
            title:'班级简称',
            align:"center",
            dataIndex: 'classNickname'
          },
          {
            title:'班级总人数',
            align:"center",
            dataIndex: 'classStudentAllCount'
          }

        ],
        dongtaiColumns : [
          {
            title:'分项项目',
            align:"center",
            dataIndex: 'exaPapProItemName',  //列名
            dataIndexId: 'exaPapProItemName',  //绑定数据字段
            nulldatacolname: '其他',
            valueIndex: 'classAvgScore'      //数据值取值字段
          }
        ],
        //动态列值
        // dongtaiColumnsValue : [
        //   {
        //     title:'班级平均分',
        //     align:"center",
        //     dataIndex: 'classAvgScore'
        //   },
        //   {
        //     title:'计分(参考)人数',
        //     align:"center",
        //     dataIndex: 'classStudentExamCount'
        //   },
        //   {
        //     title:'优良率分析',
        //     align:"center",
        //     dataIndex: 'analysisYlv'
        //   },
        //   {
        //     title:'优良人数分析',
        //     align:"center",
        //     dataIndex: 'analysisYlrs'
        //   },
        //   {
        //     title:'考试描述',
        //     align:"center",
        //     dataIndex: 'classExamDescribe'
        //   },
        //   {
        //     title:'年级排名',
        //     align:"center",
        //     dataIndex: 'gradeAchiRank'
        //   }
        // ],
        url: {
          list: "/analysisachievement/achclasses/achClassSubjectProjScore/list",
          // delete: "/analysisachievement/achclasses/achClassSubjectProjScore/delete",
          // deleteBatch: "/analysisachievement/achclasses/achClassSubjectProjScore/deleteBatch",
          exportXlsUrl: "/analysisachievement/achclasses/achClassSubjectProjScore/exportXls",
          // importExcelUrl: "analysisachievement/achclasses/achClassSubjectProjScore/importExcel",

        },
        dictOptions:{},
        superFieldList:[],
        //动态列：行转列
        tableHeader: {  }, //绑定表头
        tableBody: { } //绑定数据

      }
    },
    created() {
    this.getSuperFieldList();
      this.trRow2ColInitColumns(null);//初始化列
      // this.initColumns();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'gradeName',text:'年级',dictCode:''})
        fieldList.push({type:'string',value:'examinationName',text:'考试',dictCode:''})
        fieldList.push({type:'string',value:'examinationPaperName',text:'试卷',dictCode:''})
        fieldList.push({type:'string',value:'subjectName',text:'科目',dictCode:''})
        fieldList.push({type:'string',value:'className',text:'班级',dictCode:''})
        fieldList.push({type:'string',value:'classNickname',text:'班级简称',dictCode:''})
        fieldList.push({type:'string',value:'exaPapProItemName',text:'试卷',dictCode:''})
        fieldList.push({type:'int',value:'classStudentAllCount',text:'班级总人数',dictCode:''})
        fieldList.push({type:'int',value:'classStudentExamCount',text:'计分(参考)人数',dictCode:''})
        fieldList.push({type:'double',value:'classAvgScore',text:'班级平均分',dictCode:''})
        fieldList.push({type:'Text',value:'analysisYlv',text:'优良率分析',dictCode:''})
        fieldList.push({type:'Text',value:'analysisYlrs',text:'优良人数分析',dictCode:''})
        fieldList.push({type:'Text',value:'classExamDescribe',text:'考试描述',dictCode:''})
        fieldList.push({type:'int',value:'gradeAchiRank',text:'年级排名',dictCode:''})
        this.superFieldList = fieldList
      },
      //查询条件联动begin //////////////////////////////////////////////////////////////
      //初始化科目信息
      async initsubjectList() {
        let subjectList = await getSubjectList()
        if (subjectList.code === 200) {
          this.subjectList = []
          subjectList.result.forEach(item => {
            this.subjectList.push({
              label: item.subjectName,
              value: item.subjectId
            })
          })
        }
      },
      //科目变更-->更新教师列表
      async handleSubjectChange() {
        let tenantId = ''
        if (localStorage.length > 0) {
          let localData = JSON.parse(localStorage.getItem('pro__Login_Userinfo'))
          tenantId = localData.value.tenantId
          this.queryParam.tenantId = tenantId
        }
        let params = {
          tenantId: tenantId,
          subjectId: this.queryParam.subjectId
        }
        this.getTeacherLists(params)
        // let res = await queryTeacherListBySubject(params)
        // if (res.success) {
        //   this.teacherList = []
        //   res.result.forEach(item => {
        //     this.teacherList.push({
        //       value: item.teacherId,
        //       label: item.teacherName
        //     })
        //   })
        // }

      },
      //初始化教师
      async getTeacherLists(params){
        var teaparams;
        if(params){ //如果参数存在
          teaparams = params;
        }
        else{ //如果参数不存在
          let tenantId = ''
          if (localStorage.length > 0) {
            let localData = JSON.parse(localStorage.getItem('pro__Login_Userinfo'))
            tenantId = localData.value.tenantId
            this.queryParam.tenantId = tenantId
          }
          teaparams = {
            tenantId: tenantId,
            subjectId: null
          }
        }

        let res = await queryTeacherListBySubject(teaparams)
        if (res.success) {
          this.teacherList = []
          res.result.forEach(item => {
            this.teacherList.push({
              value: item.teacherId,
              label: item.teacherName
            })
          })
        }
      },
      //更改年级-->选择考试，选择班级
      changeGradeId(){
        if( this.queryParam.gradeId   ){ //判断不为空
          this.queryParamSelect.examinationIdSelect = "ach_examination,examination_name,id,del_flag  =0 and iz_open  =1 and grade_id=\'"+ this.queryParam.gradeId + "\' order by create_time  desc" ;
          this.queryParamSelect.classIdSelect = "cou_class,class_name,id,class_iz_open  =1 and class_iz_delete  = 0 and grade_code=\'"+ this.queryParam.gradeId + "\' order by  class_order" ;
        }
      },
      //更改考试-->选择试卷
      changeExaminationId(){
        if(this.queryParam.examinationId  ){
          this.queryParamSelect.examinationPaperIdSelect = "ach_examination_paper aep,aep.examination_paper_name,aep.id,aep.iz_open =1 and aep.del_flag =0 and aep.examination_id =\'"+ this.queryParam.examinationId + "\'  order by aep.examination_paper_name" ;
          // this.queryParamSelect.achievementStandardIdSelect = "ach_achievement_standard,achievement_standard_name,id,iz_open =1 and del_flag =0  order by achievement_standard_order",
          // this.queryParamSelect.examinationIdSelect = "ach_examination,examination_name,id,del_flag  =0 and iz_open  =1 and grade_id='"+ this.queryParam.gradeId +"' order by create_time  desc"
        }
      },
      //更改试卷-->选择标准
      changeExaminationPaperId(){
        if(this.queryParam.examinationPaperId){
          this.queryParamSelect.achievementStandardIdSelect = "ach_achievement_standard aas inner join rel_ach_standard_distribution rasd on aas.id = rasd.achievement_standard_id,aas.achievement_standard_name,aas.id,aas.iz_open =1 and aas.del_flag =0 and rasd.paper_standard_effective =1 and  rasd.rel_obj_id=\'"+this.queryParam.examinationPaperId+"\'" ;
        }
      },
      //更改标准-->选择标准分项
      changeAchievementStandardId(){
        if(this.queryParam.achievementStandardId){
          this.queryParamSelect.achieveStandardItemIdSelect = "ach_achieve_standard_item,stand_item_name,id,iz_open =1 and del_flag =0 and achievement_standard_id = \'"+this.queryParam.achievementStandardId+"\' order by exa_pap_pro_item_code" ;
        }
      },
      //查询条件联动end //////////////////////////////////////////////////////////////


      // 列设置更改事件
      onColSettingsChange (checkedValues) {
        var key = this.$route.name+":colsettings";
        console.log(key);
        Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
        this.settingColumns = checkedValues;
        const cols = this.defColumns.filter(item => {
          if(item.key =='rowIndex'|| item.dataIndex=='action'){
            return true
          }
          if (this.settingColumns.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns =  cols;
      },


      async initColumns(){
        //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

        var key = this.$route.name+":colsettings";
        let colSettings= Vue.ls.get(key);
        if(colSettings==null||colSettings==undefined){
          // this.trRow2Col();
          let allSettingColumns = [];
          this.defColumns.forEach(function (item,i,array ) {
            allSettingColumns.push(item.dataIndex);
          })
          this.settingColumns = allSettingColumns;
          this.columns = this.defColumns;
        }else{
          this.settingColumns = colSettings;
          const cols = this.defColumns.filter(item => {
            if(item.key =='rowIndex'|| item.dataIndex=='action'){
              return true;
            }
            if (colSettings.includes(item.dataIndex)) {
              return true;
            }
            return false;
          })
          this.columns =  cols;
        }
      },
      trRow2ColUtil(testdata) {
        console.log("1111111111111111111111");
        console.log(testdata);
        //第一次遍历，制做 tableHeader
        var th = {}
        th["classId"] = '班级id';  //固定列
        th["className"] = '班级';

        //筛选科目
        var thKey = {}
        for (var i = 0; i < testdata.length; i++) {
          thKey[testdata[i].subjectName] = 1;  //动态列
        }

        //把科目加到th里面 ，动态增长列
        for (var key in thKey) {
          th[key] = key;
        }

        this.tableHeader = th;

        //第二次遍历，制做tr的行
        var tr = {};
        for (var i = 0; i < testdata.length; i++) {
          var d = testdata[i];
          tr['s' + d.classId] = {
            classId: d.classId, //固定列
            className: d.className
          }
        }
        //第三次遍历，添加科目的成绩
        for (var i = 0; i < testdata.length; i++) {
          var d = testdata[i];

          tr['s' + d.classId][d.subjectName] = d.classAvgScore + 100;  //动态列
        }

        this.tableBody = tr;
      },

      trRow2ColUtil2(testdata) {
            console.log("1111111111111111111111");
            console.log(testdata);
            //第一次遍历，制做 tableHeader
            var th = {}; //表头
            var thKeyCol = {}; //动态关键列

            //固定列
            // th["className"] = '班级';
            th["gradeName"] = '年级';  //固定列
            th["classNickname"] = '班级';
            th["examinationName"] = '考试';
            th["examinationPaperName"] = '试卷';
            th["subjectName"] = '科目';
            // th["exaPapProItemName"] = '分项';
            th["classStudentAllCount"] = '班级总人数';


            //筛选科目分项
            var thKey = {}
            for (var i = 0; i < testdata.length; i++) {
              thKey[testdata[i].exaPapProItemName] = 1;  //动态列
            }

            //把科目加到th里面 ，动态增长列
            for (var key in thKey) {
              th[key] = key;
              thKeyCol[key] = key;
            }

            this.tableHeader = th;

            //第二次遍历，制做tr的行
            var tr = {}; //数据

            for (var i = 0; i < testdata.length; i++) {
              var d = testdata[i];
              tr['s' + d.classId] = {
                // classId: d.classId, //固定列
                // className: d.className;
                gradeName : d.gradeName,  //固定列
                classNickname : d.classNickname,
                examinationName : d.examinationName,
                examinationPaperName : d.examinationPaperName,
                subjectName : d.subjectName,
                // exaPapProItemName : d.exaPapProItemName,
                classStudentAllCount : d.classStudentAllCount
              }
            }
            //第三次遍历，添加科目的成绩
            console.log(this.tableHeader)
              for (var i = 0; i < testdata.length; i++) {
              var d = testdata[i];
              for (var key in thKeyCol ){
                if (d.exaPapProItemName == key ) {
                  tr['s' + d.classId][d.exaPapProItemName] = d.classAvgScore ;  //动态列
                }
                else if (tr['s' + d.classId][key] == undefined || tr['s' + d.classId][key] ==null || tr['s' + d.classId][key] == ''){
                  //补充其他学科为空值
                  tr['s' + d.classId][key] = null;
                }
                else if(tr['s' + d.classId][key] != null){
                  continue;//已经有值了，无需处理
                }
                else{
                  //补充其他学科为空值
                  tr['s' + d.classId][key] = -1;
                }
              }
            }

            this.tableBody = tr;

              console.log('2222222222222');
              console.log(this.columns);
              console.log(this.dataSource);
        console.log(this.tableHeader);
        console.log(this.tableBody);
          },

      trRow2ColUtil3(testdata) {
        console.log("1111111111111111111111");
        console.log(testdata);
        //第一次遍历，制做 tableHeader
        var th = this.gudingColumns; //表头 [{}]
        var thKeyCol = {}; //动态关键列,需重新定义，动态获取


        //筛选科目分项
        var thKey = {}
        for (var i = 0; i < testdata.length; i++) {
          var d = testdata[i];
          var dontaicolName = this.dongtaiColumns[0].dataIndex;
          var dontaicolId = this.dongtaiColumns[0].dataIndexId;
          if(  d[dontaicolName] != undefined && d[dontaicolName] != null && d[dontaicolName] != 'null' && d[dontaicolName] != '' ){
            // thKey[d[dontaicolName] ] =1 ;
              thKey[d[dontaicolName] ] = d[dontaicolId];  //动态列

            // thKey[eval("d."+dontaicolId)] =2;
          }
          else if(d[dontaicolName] == null || d[dontaicolName] != 'null' || d[dontaicolName] != ''){
            thKey[this.dongtaiColumns[0].nulldatacolname ] = this.dongtaiColumns[0].nulldatacolname;  //动态列

          }
          else{
            thKey['-1'] = '-1';
          }

          // if(  d[dontaicolId] != undefined && d[dontaicolId] != null && d[dontaicolId] != 'null' && d[dontaicolId] != '' ){
          //   thKey[d[dontaicolId] ] = 2;  //动态列
          // }

        }

        //把科目加到th里面 ，动态增长列
        // for (var key in Object.keys(thKey))
        for (var key in thKey){
          var colobj = { title: key, align:"center",dataIndex:thKey[key]};
          th.push(colobj) ;
          thKeyCol[key] = key;
        }
        // this.tableHeader = th;
        // this.columns = th; //重新定义列，增加动态列
        if (this.defColumns == undefined || this.defColumns == null || this.defColumns.length ==0 ){
          this.defColumns = th;
        }
        // if (this.columns == undefined || this.columns == null){
        //   this.columns = th;
        // }

        //第二次遍历，制做tr的行
        var tr = []; //数据 [{}]

        for (var i = 0; i < testdata.length; i++) {
          var d = testdata[i];
          var rowdata = {};
          for(var j=0;j< this.gudingColumns.length;j++){
            rowdata[this.gudingColumns[j].dataIndex] = d[this.gudingColumns[j].dataIndex]; //用对应列的数据赋值给固定列
          }


          //判断对象是否存在，存在则忽略，不存在则插入
          if ( tr.length == 0 ){
            tr.push(rowdata)
          }
          else{
            var insertflag = true;
            for(var k in tr ){
              var eqflag = true;
              for(var rd in rowdata ){
                if(rowdata[rd] !== tr[k][rd]){
                  eqflag = false;
                  continue;
                }
              }
              //判断是否相等
              // if (Object.is(rowdata,tr[k])){
              // if ( this.compare(rowdata,tr[k]) ){
              if ( eqflag ){
                insertflag = false;
              }
              else{
                continue;
              }
            }
            //应当插入则插入：即不存在则插入
            if(insertflag){
              tr.push(rowdata)
            }
          }

        }
        //第三次遍历，添加科目的成绩
        for (var i = 0; i < testdata.length; i++) {
          var d = testdata[i];
          //查找应该是tr的第几条数据
          var trindex = -1;
          for(var ti=0;ti<tr.length;ti++){
            var tr_rowdata = tr[ti];//取出1条数据
            var equalflag = true;
            for(var j=0;j< this.gudingColumns.length;j++){
              if (tr_rowdata[this.gudingColumns[j].dataIndex] != d[this.gudingColumns[j].dataIndex]){ //用对应列的数据赋值给固定列
                equalflag = false;
              }
            }
            //如果相等即找到了,则写入数据,考虑动态列寻找
            if(equalflag ){
              //直接赋值：给对应动态列的值设置为成绩数值（会存在空值串列的情况，需考虑空值设置问题）
              //考虑到数据是通过列名绑定，就不会存在串列问题
              if ( d[this.dongtaiColumns[0].dataIndexId] != undefined && d[this.dongtaiColumns[0].dataIndexId] != null && d[this.dongtaiColumns[0].dataIndexId] != '' ){
                tr_rowdata[d[this.dongtaiColumns[0].dataIndexId]] = d[this.dongtaiColumns[0].valueIndex]; //把成绩数据绑定到动态列名上
              }
              else{
                tr_rowdata[this.dongtaiColumns[0].nulldatacolname] = d[this.dongtaiColumns[0].valueIndex]; //把成绩数据绑定到动态列名上
              }



              //通过循环判断，确定应该给哪个动态列赋值（避免空值串列问题）
              // for (var key in thKeyCol ){
              //   if (d[this.dongtaiColumns[0].dataIndex] == key ) {
              //     tr_rowdata[d[this.dongtaiColumns[0].dataIndexId]] = d[this.dongtaiColumnsValue[0].dataIndex] ;  //动态列的成绩数值
              //   }
              //   else if (tr_rowdata[key] == undefined || tr_rowdata[key] ==null || tr_rowdata[key] == ''){
              //     //补充其他学科为空值
              //     tr_rowdata[key] = null;
              //   }
              //   else if(tr_rowdata[key] != null){
              //     continue;//已经有值了，无需处理
              //   }
              //   else{
              //     //补充其他学科为-1异常情况
              //     tr_rowdata[key] = -1;
              //   }
              // }
            }
            tr[ti] = tr_rowdata; //重新定义一行数据，把动态列数据加入进来
          }

        }

        // this.tableBody = tr;
        this.dataSource = tr;  //重新定义数据：用分组动态列进行行列转换后的新数据



        console.log('333333333333333');
        console.log(this.columns);
        console.log(this.dataSource);
      }
          ,
      trRow2ColInitColumns(testdata){
        if(testdata == undefined || testdata == null ){
          var params = this.getQueryParams();//查询条件
          getAction(this.url.list,params).then((res) => {
            if (res.success){
              testdata = res.result.records;
              // this.trRow2ColUtil3(testdata);
              this.trRow2ColInitColumns(testdata);
            }
          });
        }
        //第一次遍历，制做 表头
        var th = this.gudingColumns; //表头 [{}]
        var thKeyCol = {}; //动态关键列,需重新定义，动态获取


        //筛选科目分项
        var thKey = {}
        for (var i = 0; i < testdata.length; i++) {
          var d = testdata[i];
          var dontaicolName = this.dongtaiColumns[0].dataIndex;
          var dontaicolId = this.dongtaiColumns[0].dataIndexId;
          if(  d[dontaicolName] != undefined && d[dontaicolName] != null && d[dontaicolName] != 'null' && d[dontaicolName] != '' ){
            // thKey[d[dontaicolName] ] =1 ;
            thKey[d[dontaicolName] ] = d[dontaicolId];  //动态列

            // thKey[eval("d."+dontaicolId)] =2;
          }
          else if(d[dontaicolName] == null || d[dontaicolName] != 'null' || d[dontaicolName] != ''){
            thKey[this.dongtaiColumns[0].nulldatacolname ] = this.dongtaiColumns[0].nulldatacolname;  //动态列

          }
          else{
            thKey['-1'] = '-1';
          }

          // if(  d[dontaicolId] != undefined && d[dontaicolId] != null && d[dontaicolId] != 'null' && d[dontaicolId] != '' ){
          //   thKey[d[dontaicolId] ] = 2;  //动态列
          // }

        }

        //把科目加到th里面 ，动态增长列
        // for (var key in Object.keys(thKey))
        for (var key in thKey){
          var colobj = { title: key, align:"center",dataIndex:thKey[key]};
          th.push(colobj) ;
          thKeyCol[key] = key;
        }
        // this.tableHeader = th;
        // this.columns = th; //重新定义列，增加动态列
        if (this.defColumns == undefined || this.defColumns == null || this.defColumns.length ==0 ){
          this.defColumns = th;
          this.initColumns();
        }
        // if (this.columns == undefined || this.columns == null){
        //   this.columns = th;
        // }
      },
      trRow2ColInitDatas(testdata){
        //第二次遍历，制做tr的行
        var tr = []; //数据 [{}]

        for (var i = 0; i < testdata.length; i++) {
          var d = testdata[i];
          var rowdata = {};
          for(var j=0;j< this.gudingColumns.length;j++){
            rowdata[this.gudingColumns[j].dataIndex] = d[this.gudingColumns[j].dataIndex]; //用对应列的数据赋值给固定列
          }


          //判断对象是否存在，存在则忽略，不存在则插入
          if ( tr.length == 0 ){
            tr.push(rowdata)
          }
          else{
            var insertflag = true;
            for(var k in tr ){
              var eqflag = true;
              for(var rd in rowdata ){
                if(rowdata[rd] !== tr[k][rd]){
                  eqflag = false;
                  continue;
                }
              }
              //判断是否相等
              // if (Object.is(rowdata,tr[k])){
              // if ( this.compare(rowdata,tr[k]) ){
              if ( eqflag ){
                insertflag = false;
              }
              else{
                continue;
              }
            }
            //应当插入则插入：即不存在则插入
            if(insertflag){
              tr.push(rowdata)
            }
          }

        }
        //第三次遍历，添加科目的成绩:动态插入数据列
        for (var i = 0; i < testdata.length; i++) {
          var d = testdata[i];
          //查找应该是tr的第几条数据
          var trindex = -1;
          for(var ti=0;ti<tr.length;ti++){
            var tr_rowdata = tr[ti];//取出1条数据
            var equalflag = true;
            for(var j=0;j< this.gudingColumns.length;j++){
              if (tr_rowdata[this.gudingColumns[j].dataIndex] != d[this.gudingColumns[j].dataIndex]){ //用对应列的数据赋值给固定列
                equalflag = false;
              }
            }
            //如果相等即找到了,则写入数据,考虑动态列寻找
            if(equalflag ){
              //直接赋值：给对应动态列的值设置为成绩数值（会存在空值串列的情况，需考虑空值设置问题）
              //考虑到数据是通过列名绑定，就不会存在串列问题
              if ( d[this.dongtaiColumns[0].dataIndexId] != undefined && d[this.dongtaiColumns[0].dataIndexId] != null && d[this.dongtaiColumns[0].dataIndexId] != '' ){
                tr_rowdata[d[this.dongtaiColumns[0].dataIndexId]] = d[this.dongtaiColumns[0].valueIndex]; //把成绩数据绑定到动态列名上
              }
              else{
                tr_rowdata[this.dongtaiColumns[0].nulldatacolname] = d[this.dongtaiColumns[0].valueIndex]; //把成绩数据绑定到动态列名上
              }



              //通过循环判断，确定应该给哪个动态列赋值（避免空值串列问题）
              // for (var key in thKeyCol ){
              //   if (d[this.dongtaiColumns[0].dataIndex] == key ) {
              //     tr_rowdata[d[this.dongtaiColumns[0].dataIndexId]] = d[this.dongtaiColumnsValue[0].dataIndex] ;  //动态列的成绩数值
              //   }
              //   else if (tr_rowdata[key] == undefined || tr_rowdata[key] ==null || tr_rowdata[key] == ''){
              //     //补充其他学科为空值
              //     tr_rowdata[key] = null;
              //   }
              //   else if(tr_rowdata[key] != null){
              //     continue;//已经有值了，无需处理
              //   }
              //   else{
              //     //补充其他学科为-1异常情况
              //     tr_rowdata[key] = -1;
              //   }
              // }
            }
            tr[ti] = tr_rowdata; //重新定义一行数据，把动态列数据加入进来
          }

        }

        this.dataSource = tr;  //重新定义数据：用分组动态列进行行列转换后的新数据

      },
      async trRow2Col(){
        //获得测试数据
        // var testdata = this.dataSource ;
        var testdata = [];

        var params = this.getQueryParams();//查询条件
        getAction(this.url.list,params).then((res) => {
          if (res.success){
            testdata = res.result.records;
            // this.trRow2ColUtil3(testdata);
            // this.trRow2ColInitColumns(testdata); //列名已经初始化了，只需初始化1次，不必重复初始化
            this.trRow2ColInitDatas(testdata);  //更新数据样式格式

          }
        });



      }
      ,
       compare(Obj_1,Obj_2) {

        var state = true;

        for (var key in Obj_1) {

          if (typeof (Obj_2[key]) === 'undefined') {

            state = false;

          } else {

            if (typeof (Obj_1[key]) === 'object') {

              state = compare(Obj_1[key],Obj_2[key]);

            } else {

              if (Obj_1[key] !== Obj_2[key]) {

                state = false;

              }

            }

          }

        }

        return state;

      }
// 对Object扩展一个方法chargeObjectEqual
// Object.prototype.chargeObjectEqual = function(obj){
//   // 当前Object对象
//   var propsCurr = Object.getOwnPropertyNames(this);
//   // 要比较的另外一个Object对象
//   var propsCompare = Object.getOwnPropertyNames(obj);
//   if (propsCurr.length != propsCompare.length) {
//     return false;
//   }
//   for (var i = 0,max = propsCurr.length; i < max; i++) {
//     var propName = propsCurr[i];
//     if (this[propName] !== obj[propName]) {
//       return false;
//     }
//   }
//   return true;
// }
    }
  }
</script>




<!--// 对比JS中两个对象是否相等,深度对比-->
<!--// function deepCompare(x, y) {-->
<!--//   var i, l, leftChain, rightChain;-->
<!--//-->
<!--//   function compare2Objects(x, y) {-->
<!--//     var p;-->
<!--//-->
<!--//     // remember that NaN === NaN returns false-->
<!--//     // and isNaN(undefined) returns true-->
<!--//     if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {-->
<!--//       return true;-->
<!--//     }-->
<!--//-->
<!--//     // Compare primitives and functions.-->
<!--//     // Check if both arguments link to the same object.-->
<!--//     // Especially useful on the step where we compare prototypes-->
<!--//     if (x === y) {-->
<!--//       return true;-->
<!--//     }-->
<!--//-->
<!--//     // Works in case when functions are created in constructor.-->
<!--//     // Comparing dates is a common scenario. Another built-ins?-->
<!--//     // We can even handle functions passed across iframes-->
<!--//     if ((typeof x === 'function' && typeof y === 'function') ||-->
<!--//       (x instanceof Date && y instanceof Date) ||-->
<!--//       (x instanceof RegExp && y instanceof RegExp) ||-->
<!--//       (x instanceof String && y instanceof String) ||-->
<!--//       (x instanceof Number && y instanceof Number)) {-->
<!--//       return x.toString() === y.toString();-->
<!--//     }-->
<!--//-->
<!--//     // At last checking prototypes as good as we can-->
<!--//     if (!(x instanceof Object && y instanceof Object)) {-->
<!--//       return false;-->
<!--//     }-->
<!--//-->
<!--//     if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {-->
<!--//       return false;-->
<!--//     }-->
<!--//-->
<!--//     if (x.constructor !== y.constructor) {-->
<!--//       return false;-->
<!--//     }-->
<!--//-->
<!--//     if (x.prototype !== y.prototype) {-->
<!--//       return false;-->
<!--//     }-->
<!--//-->
<!--//     // Check for infinitive linking loops-->
<!--//     if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {-->
<!--//       return false;-->
<!--//     }-->
<!--//-->
<!--//     // Quick checking of one object being a subset of another.-->
<!--//     // todo: cache the structure of arguments[0] for performance-->
<!--//     for (p in y) {-->
<!--//       if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {-->
<!--//         return false;-->
<!--//       } else if (typeof y[p] !== typeof x[p]) {-->
<!--//         return false;-->
<!--//       }-->
<!--//     }-->
<!--//-->
<!--//     for (p in x) {-->
<!--//       if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {-->
<!--//         return false;-->
<!--//       } else if (typeof y[p] !== typeof x[p]) {-->
<!--//         return false;-->
<!--//       }-->
<!--//-->
<!--//       switch (typeof(x[p])) {-->
<!--//         case 'object':-->
<!--//         case 'function':-->
<!--//-->
<!--//           leftChain.push(x);-->
<!--//           rightChain.push(y);-->
<!--//-->
<!--//           if (!compare2Objects(x[p], y[p])) {-->
<!--//             return false;-->
<!--//           }-->
<!--//-->
<!--//           leftChain.pop();-->
<!--//           rightChain.pop();-->
<!--//           break;-->
<!--//-->
<!--//         default:-->
<!--//           if (x[p] !== y[p]) {-->
<!--//             return false;-->
<!--//           }-->
<!--//           break;-->
<!--//       }-->
<!--//     }-->
<!--//-->
<!--//     return true;-->
<!--//   }-->
<!--//-->
<!--//   if (arguments.length < 1) {-->
<!--//     return true; //Die silently? Don't know how to handle such case, please help...-->
<!--//     // throw "Need two or more arguments to compare";-->
<!--//   }-->
<!--//-->
<!--//   for (i = 1, l = arguments.length; i < l; i++) {-->
<!--//-->
<!--//     leftChain = []; //Todo: this can be cached-->
<!--//     rightChain = [];-->
<!--//-->
<!--//     if (!compare2Objects(arguments[0], arguments[i])) {-->
<!--//       return false;-->
<!--//     }-->
<!--//   }-->
<!--//-->
<!--//   return true;-->
<!--// }-->



<style scoped>
  @import '~@assets/less/common.less';
</style>